<template>
	<div class="question-bank" v-loading.fullscreen.lock="loading"
		element-loading-text="拼命加载中">
		<div class="question-bank-h-box">
			<div class="question-bank-h-path">
				<router-link to="/test/item-bank">公共题库</router-link>
				<router-link to="/test/private-bank">我的题库</router-link>
			</div>

			<ul class="question-bank-h-type">

				<li class="question-bank-h-list">
					<span>题型:</span>
					<div>
						<template>
						  <el-radio-group v-model="question.type"  @change="getTestList">
						  	<template v-for="item of questionTypeList">
						  		<el-radio :key="item.id" :label="item.id">{{item.name}}</el-radio>
						  	</template>
						  </el-radio-group>
						</template>
					</div>
				</li>

				<li class="question-bank-h-list">
					<span>难度:</span>
					<div>
						<template>
						  <el-radio-group v-model="question.difficulty"  @change="getTestList">
						    <el-radio :label="0">全部</el-radio>
						    <el-radio :label="11">容易</el-radio>
						    <el-radio :label="12">普通</el-radio>
						    <el-radio :label="13">困难</el-radio>
						  </el-radio-group>
						</template>
					</div>
				</li>

				<li class="question-bank-h-list">
					<span>题目范围:</span>
					<div class="question-area">
                        <testArea ref="testArea"></testArea>
						<el-button type="primary" @click="screenChange()">筛选</el-button>
						<el-button type="primary" plain @click="restChange()">重置</el-button>
					</div>
				</li>

			</ul>
		</div>	
		
		<div class="question-bank-wp">
			
			<div class="question-bank-wp-l">
				<el-tabs v-model="activeName" @tab-click="handleClick">
				   <el-tab-pane label="选择章节" name="1">
				   		<el-input class="filterText" v-show="chapterList.length > 0"
				   		  placeholder="输入关键字进行过滤" clearable
				   		  v-model="filterText">
				   		</el-input>
				   		<el-scrollbar>
				   			<el-tree class="question-tree"
				   			  :data="chapterList"
				   			  show-checkbox
				   			  node-key="id" ref="tree"
				   			  default-expand-all
				   			  :filter-node-method="filterNode"
				   			  :default-expanded-keys="[]"
				   			  :default-checked-keys="[]"
				   			  :props="defaultProps"
				   			  @check="handleCheckChange">
				   			</el-tree>
				   		</el-scrollbar>
				   </el-tab-pane>
				   <el-tab-pane label="选择知识点" name="2">
					   	<el-input class="filterText" v-show="chapterList.length > 0"
					   		placeholder="输入关键字进行过滤" clearable
					   		v-model="filterText2">
					   	</el-input>
					   	<el-scrollbar>
					   		<el-tree class="question-tree"
					   		:data="chapterList"
					   		show-checkbox
					   		node-key="id" ref="tree2"
					   		default-expand-all
					   		:filter-node-method="filterNode"
					   		:default-expanded-keys="[]"
					   		:default-checked-keys="[]"
					   		:props="defaultProps"
					   		 @check="handleCheckChange">
					   	</el-tree>
					   </el-scrollbar>
				   </el-tab-pane>

				 </el-tabs>

			</div>


			<div class="question-bank-wp-r">
				

				<div class="question-bank-wp-r-h">
					<el-input
					    placeholder="搜索试题"
					    suffix-icon="el-icon-search"
					    v-model="question.keyword"  @change="getTestList">
					  </el-input>

					  <div>
						  	<el-radio-group v-model="question.order" @change="getTestList">
						  		<el-radio label="time">最新<i class="el-icon-sort-down"></i></el-radio>
						  		<el-radio label="fav">热门<i class="el-icon-sort-down"></i></el-radio>
						  	</el-radio-group>
					  </div>
				</div>

				<div class="question-bank-ls">

					<ul class="preview-conten-subject">

						<template v-for="(item, index) of testList">
							<transition name="el-zoom-in-top">
							<li class="preview-conten-subject-c" :key="index">
								<template>
									<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
										<i>{{index+1}}. </i>
										<span v-html="item.content"></span>
										<strong v-if="item.score">({{item.score}}分)</strong>
									</div>
									<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
										<i>{{index+1}}. </i>
										<span v-html="item.content"></span>
										<strong v-if="item.score">({{item.score}}分)</strong>
									</div>
								</template>

								<el-collapse accordion class="preview-answer">
									<el-collapse-item>
										<template slot="title">
											<div class="preview-accordion-title">
												<span>题型：{{item.question_type}}</span>
												<span>难度： {{item.difficulty}}</span>
												<span v-if="item.keynote == 1">重点程度： 低</span>
												<span v-if="item.keynote == 2">重点程度： 中</span>
												<span v-if="item.keynote == 3">重点程度： 高</span>
											</div>
											<div class="accordion-operate" v-if="item.create_id != $g.user_id">
												<a class="accordion-"  @click.stop="operationTest(item.id)">添加到我的题库</a>
											</div>
										</template>
										
										<ul class="preview-topic" v-if="item.option">
											<template v-for="(option,index2) of item.option">
												<li class="preview-subject-title preview-false option-pattern" v-if="item.type_base_id === 4"  :key="index2">
													<template >
														<el-checkbox disabled :label="option.name"></el-checkbox>
													</template>
												</li>
												<template v-else>
													<li class="preview-subject-title preview-false" v-if="item.pattern === 1" :key="index2">
														<template>
															<el-checkbox disabled :label="option.name"></el-checkbox>
															<div  v-html="option.value"></div>
														</template>
													</li>
													<li class="preview-subject-title preview-false option-pattern" v-if="item.pattern === 2"  :key="index2">
														<template >
															<el-checkbox disabled :label="option.name"></el-checkbox>
															<!-- <div  v-html="option.value"></div> -->
														</template>
													</li>
												</template>
											</template>
										</ul>

										<div class="preview-accordion-answer" v-if="item.type_base_id == 1 || item.type_base_id == 2 || item.type_base_id == 4">

											<span style="line-height: 28px">正确答案： </span>
											<template v-if="item.type_base_id == 4">
												<div v-if="item.answer"><i>{{item.answer[0]}}</i></div>
											</template>
											<template v-else-if="item.type_base_id == 1 || item.type_base_id == 2">
												<div><i v-for="answer of item.answer">{{answer}}</i></div>
											</template>
											
										</div>
										<div class="preview-accordion-answer">
											<span>统计： </span>
											<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
										</div>
										<div class="preview-accordion-answer">
											<span>解析： </span>
											<template v-if="item.pattern == 1">
												<div v-html="item.resolve"></div>
											</template>
											<template v-if="item.pattern == 2">
												<div>
													<img :src="BASE_URL + item.resolve_image_path">
												</div>
											</template>
										</div>
									</el-collapse-item>
								</el-collapse>
							</li>
							</transition>
						</template>

					</ul>

					<el-pagination class="test-pagination" v-show=" question.total > 10"
						@size-change="sizeChange"
						@current-change="currentChange"
						:current-page="question.page"
						:page-sizes="[10, 50, 100, 200, 300, 400]"
						:page-size="question.size"
						layout="total, sizes, prev, pager, next, jumper"
						:total="question.total">
					</el-pagination>
				</div>

				<div class="dependent" v-if="placeholder">
				    <i class="ipng image_state01"></i>
				    <p>还没发现任何相关的内容哦~</p>
				</div>
			</div>
		</div>
		

		<!-- 预览图片 -->
		<image-viewer 
            v-if="imagePreview.showViewer"
            :initial-index="imageIndex"
            :on-close="closeViewer"
            :url-list="imagePreview.previewSrcList">
        </image-viewer>
	</div>
</template>

<script>
    import testArea  from  './test-area';
	export default {
        components: {
            testArea
        },      
		data(){
			return {
				imagePreview: {/*图片预览*/
					showViewer: false,
					previewSrcList: []
				},
				loading: true,
				placeholder: false,
				question: {
					difficulty: 0,  /*难度*/
					type: 0, 		/*试题类型*/
					order: 'time',			/*列表排序*/
					keyword: '', 			/*搜索关键字*/
					page: 1,
					size: 10,
					total: 0
				},

				testList: [], 		/*试卷列表*/
				chapterList: [], 	/* 章节列表*/
				knowledgeList: [],	/*知识点*/
				activeName: '1',	
				filterText: '',		/*章节的关键词*/
				filterText2: '',	/*知识点的关键词*/
				chapterID: [],		/*章节 & 知识点 选中的id*/
				knowledgeID: [],
				questionTypeList: [],
				defaultProps: {
					children: 'children',
					label: 'name'
				},
				imgIndex: 0,
			}
		},

		watch: {
			'$store.state.questionChange': {
				handler(val, newval){
                    this.$nextTick(()=>{
                        this.$refs.testArea.subjectData = deep_clone(this.$parent.subjectArr);
                        let subject = this.$route.query.subject ? this.$route.query.subject : sessionStorage.getItem('subjectID');
						this.$refs.testArea.ruleForm.subject = subject === '0' ? '' : +subject;
                        this.getTestList();     
                    })
				},
				immediate: true
			},
			/*章节的关键词*/
			filterText(val) {
				this.$refs.tree.filter(val);
			},
			/*知识点的关键词*/
			filterText2(val) {
				this.$refs.tree2.filter(val);
			}
		},
		created(){
			this.getQuestionType()
		},
		mounted(){
            this.getTestList();

			document.querySelector('.question-bank-ls').addEventListener('click',  (e)=> {
				
				let [targetSrc ,imgs, srcArr, currentIdx] = ['', '', '', '']
				if (e.target.nodeName === 'IMG') {

					this.imagePreview.showViewer = true
					targetSrc = e.target.src;
					imgs = [...e.target.parentNode.children];
					srcArr = imgs.map(item=>item.currentSrc);
					currentIdx = srcArr.indexOf(targetSrc);

					this.imagePreview.previewSrcList = srcArr
					this.imgIndex = targetSrc

				}
			
			}, false)
		},
		computed: {
			imageIndex() {
			    return this.imagePreview.previewSrcList.indexOf(this.imgIndex);
			}

		},
		methods: {
			/**
			 * 关闭图片
			 * @DateTime 2020-04-16T17:40:41+0800
			 * @qiu_m
			 * @return   {[type]}                 [description]
			 */
			 closeViewer() {
			 	this.imagePreview.showViewer = false;
			 	this.imagePreview.previewSrcList = []
			 },
			 /**
			  * 重置数据
			  * @DateTime 2020-06-09T17:10:01+0800
			  * @qiu_m
			  * @return   {[type]}                 [description]
			  */
			 restChange(){
                this.$refs.testArea.setDefault();//重置题目范围select框的值
			 	this.question.page = 1
			 	this.setMaterial()
			 	this.getTestList()
			 },
			/**
			 * 筛选
			 * @qiu_m
			 * @DateTime 2019-11-16T11:53:17+0800
			 * @return   {[type]}                 [description]
			 */
			screenChange(){
                let noSelect = Object.values(this.$refs.testArea.ruleForm).includes('');
				if (noSelect) {
					this.chapterID = [];
					this.knowledgeID = [];
				}
				this.getChapter()
				this.getTestList()
			},
			/**
			 * 章节 || 知识点所对应的对象、树目前的选中状态对象
			 * @DateTime 2019-07-24T09:37:48+0800
			 * @param    {[Strong]}   data    选中的章节 || 知识点的节点对象
			 * @param    {[Array]}    checked 选中的章节 || 知识点包含 checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys 四个属性来读取选中的id,对象结构
			 */
			handleCheckChange(data, checked) {
				if (this.activeName === '1') {
					// console.log(1);
					this.chapterID = [...checked.halfCheckedKeys, ...checked.checkedKeys];
				}else{
					// console.log(2);
					this.knowledgeID = [...checked.halfCheckedKeys, ...checked.checkedKeys];
				}
				// console.log(this.chapterID, this.knowledgeID);
				this.getTestList()
			},
			/**
			 * 关键词过滤，搜索想要的条件
			 * @DateTime 2019-07-23T16:36:20+0800
			 * @param    {Strong}  value 是输入发关键字
			 * @param    [type]    data  是搜索的条件数组
			 */
			filterNode(value, data) {
				if (!value) return true;
				//根据关键字匹配数据是否存在，存在就返回对应的条件数据
				return data.name.indexOf(value) !== -1;
			},
			/**
			 * 请求试卷列表
			 * @DateTime 2019-07-22T13:47:02+0800
			 */
			getTestList(){
				let success = ( res=>{
					this.testList = res.data.data;
					this.question.page = parseInt(res.data.page_index);
					this.question.total  = parseInt(res.data.data_sum);

					// this.$nextTick(()=>{
					// 	//改变试题 img 的 url
					// 	let imgArr = document.querySelectorAll('.preview-conten-subject-c img')
					// 	let baseUrl = sessionStorage.getItem('host_addr');
					// 	for (var i = 0; i < imgArr.length; i++) {
					// 		let _temp = imgArr[i].src
					// 		imgArr[i].src = _temp.replace(location.protocol+'//'+location.host, baseUrl);
					// 	}
					// })
					this.loading = false;
					this.testList.length != 0 ? this.placeholder = false : this.placeholder = true;
				});

				let params = {
					user_id: this.$g.user_id,
					page_index: this.question.page,
					page_size: this.question.size,
                    grade_id: this.$refs.testArea.ruleForm.grade,
                    subject_id: this.$refs.testArea.ruleForm.subject,
                    version_id: this.$refs.testArea.ruleForm.edition,
                    masterial_id: this.$refs.testArea.ruleForm.material,
					keyword: this.question.keyword ,
					order: this.question.order,
					difficulty_id: this.question.difficulty,
					type_id: this.question.type,
					list_id: this.chapterID,
					know_id:  this.knowledgeID,
					authority:  1,
					type: 'default',
				};

				this.$ajax({
					url: 'api/newtest/test_question_list',
					method: 'get',
					params: params,
					func: {success: success}
				})
			},
			/**
			 * 请求题型数据
			 * @DateTime 2019-07-25T14:04:59+0800
			 * @return   {[type]}                 [description]
			 */
			getQuestionType(){

				let success = (res=>{
					this.questionTypeList = res.data;
					if (this.questionTypeList.length > 0) {
						this.questionTypeList.unshift({id: 0, name: '全部'})
					}
				});

				let params = {status: 1};

				this.$ajax({
					url: 'api/newtest/get_question_type',
					method: 'get',
					params: params,
					func: { success: success}
				})
			},
			sizeChange(val) {
				// console.log(`每页 ${val} 条`);
				this.question.size = val;
				this.getTestList()
			},
			currentChange(val) {
                document.documentElement.scrollTop = 0;
				// console.log(`当前页: ${val}`);
				this.question.page = val;
				this.getTestList()
			},
			/**
			 * type 参数对应不同的函数，
			 *
			 * 1.添加到我的题库
			 */
			operationTest(id){
				this.$confirm('是否添加到我的题库？', '提示', {
					cancelButtonText: '取消',
					confirmButtonText: '确定',
					type: 'warning',
					customClass: "test-message"
				}).then(() => {
					let success = (res=>{
						this.$message.success(res.msg)
					});

					let params = {id: id};

					this.$ajax.post('api/newtest/fav_test_question', params, {func: {success: success}})
				}).catch(() => {});
			},
			/*章节 & 知识点切换*/
			handleClick(tab, event) {
				this.chapterID = [];
				this.knowledgeID = [];
				this.getChapter();
				if (this.chapterList.length > 0 || this.knowledgeID.length > 0) {
					this.getTestList()
				}
				
			},
			/**
			 * 判断教材是否为空，在不为空时，根据id筛选相关的试题
			 * @DateTime 2019-07-24T09:27:20+0800
			 * @param    {[Strong]}   val 教材id
			 */
			setMaterial(val){
				console.log(val);
				val ? this.getChapter() : this.chapterList = [];
			},
			/**
			 * 请求章节数据
			 * @DateTime 2019-07-23T14:04:49+0800
			 * @return   {[type]}                 [description]
			 */
			getChapter(){
				if (this.$refs.testArea.ruleForm.material === '') {return};

				let success = (res=>{
					this.chapterList = res.data;
				});

				let params = {}
				if (this.activeName === '1') {
					 params = {
						material_id: this.$refs.testArea.ruleForm.material,
						type: 1
					};
				}else{
					 params = {
						material_id: this.$refs.testArea.ruleForm.material,
						type: 2
					};
				};

				let fail = (res=>{
					this.$message.error({
						duration: 8000,
						message: res.msg
					})
				})

				this.$ajax({
					url: 'api/newtest/get_list_know_by_material',
					method: 'get',
					params: params,
					func: {success: success, fail: fail}
				})
			}
			
		}

	}
</script>
